package future优化.回调版的future;

import lombok.extern.slf4j.Slf4j;

import java.util.Iterator;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;

/**
 * @author ZhuQi
 * @ClassName SuccessFlyTask
 * @Date 2022/9/5 14:40
 * @Version 1.0
 * @Description 成功的任务 回调
 */
@Slf4j
public class SuccessFlyTask implements Runnable{


    @Override
    public void run() {
        CopyOnWriteArrayList<Long> threadIds = SuccessThreadList.getThreadIds();
        while (true) {
            // 没有数据就休息
            if (threadIds.size() == 0) {
                try {
                    TimeUnit.SECONDS.sleep(1L);
                    threadIds = SuccessThreadList.getThreadIds();
                    continue;
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }

            // 遍历完成的任务

            for (int i = 0; i < threadIds.size(); i++) {
                Long threadId = threadIds.get(i);
                Future<String> futureMap = FutureMap.getFutureMap(threadId);
                try {
                    String data = futureMap.get();
                    log.info("数据为：" + data);
                    // 移除该任务
                    threadIds.remove(i);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

            // 重新赋值
            threadIds = SuccessThreadList.getThreadIds();
        }
    }
}
